<template>
  <div :element-loading-text="$t('public.loadingText')" style="height: 600px">
    <!--在线咨询右侧详情-->
    <webchat-container
      :currentBusinessObj="currentBusinessObj"
      :customer="customer"
      @videoReplay="videoReplay1"
      :tabType="tabType"
    ></webchat-container>
    <!--视频回放组件-->
    <video-replay v-if="playVideoReplay" :replayUrl="videoReplayUrl" :chatMsg="videoReplatChatMsg" @closeVideoReplay="closeVideoReplay"></video-replay>
    <!--大图组件-->
    <big-image v-if="webchatBigImage" :imageUrls="imageUrls" :bigImgUrl="bigImgUrl" @closeBigImage="closeBigImage"></big-image>
  </div>
</template>
<script>
  import WebchatContainer from '../webchat/WebchatContainer.vue'
  import videoReplay from '@/components/public-modules/popups/PopDragVideoReplay.vue'
  import bigImage from '@/components/public-modules/popups/PopDragBigImage.vue'
  import { isEmpty } from 'lodash'
  import * as gtypes from '@/store/mutation-types'
  import * as types from '@/store/modules/webchat/mutation-types'
  import bus from '@/store/eventBus'
  export default {
    name: 'WebChatSummary',
    data () {
      return {
        // tabType: 'webchat_todo',
        customerId: '',
        loading: false,
        cardLoading: true, // 从卡片点击到右边的时候的加载
        sessionId: '',
        sid: '',
        webchatBigImage: false, // 是否查看大图
        bigImgUrl: '',      // 当前大图地址
        videoReplayUrl: '', // 视频聊天记录播放地址
        playVideoReplay: false, // 是否播放视频聊天记录
        videoReplatChatMsg: '', // 当前播放的视频聊天信息
        imageUrls: [] // 聊天记录里的图片地址数组
      }
    },
    provide () {
      return {
        tabsList: [
          {
            name: 'public.customerInfo',
            tabName: 'customerInfo',
            type: 'feature',
            size: {
              width: 0,
              height: 0
            }
          }, {
            name: 'webchat.quickReplay',
            tabName: 'quickReply',
            type: 'feature',
            size: {
              width: 0,
              height: 0
            }
          }, {
            name: 'webchat.auxiliaryAgent',
            tabName: 'auxiliaryAgent',
            type: 'feature',
            size: {
              width: 0,
              height: 0
            }
          }, {
            name: 'business.newBusiness',
            tabName: 'business',
            type: 'feature',
            size: {
              width: 0,
              height: 0
            }
          }
        ]
      }
    },
    watch: {
      // 如果路由有变化，会再次执行该方法
      // 'refreshWebchatRight': 'routerChange',
      $route (to, form) {
        if (to.path.split('/')[4] !== form.path.split('/')[4] || to.path.split('/')[3] !== form.path.split('/')[3]) {
          this.playVideoReplay = false
        }
        if (to.path.split('/')[2] === 'webchat' &&
          this.cardLoading === false && (to.path.split('/')[3] !== 'webchat_all' ||
            to.path.split('/')[3] !== 'webchat_robot' ||
            to.path.split('/')[3] !== 'webchat_laterProcess' ||
            to.path.split('/')[3] !== 'webchat_queue')) {
          this.fetchData()
          this.closeBigImage()
        }
      },
      customer: {
        handler: function (val, oldVal) {
          if (val !== oldVal && !this.loading) {
            let currCustomer = {}
            if (this.$route.path.split('/')[2] === 'webchat') {
              if (this.tabType === 'webchat_todo' || this.tabType === 'webchat_all' || this.tabType === 'webchat_robot' || this.tabType === 'webchat_laterProcess' || this.tabType === 'webchat_queue') {
                currCustomer = this.$store.state.webchat.current[this.tabType].currentCustomer || {}
              }
            }
            this.customerId = currCustomer._id || ''
            let noCustomer = isEmpty(currCustomer)
            if (!noCustomer && this.$route.path.split('/').length > 4) {
              updateCurrentWebchatList(this.$store, this.sid, currCustomer)
            }
          }
        },
        deep: true
      }
    },
    computed: {
      path () {
        return this.$route.path.split('/')
      },
      type () {
        return this.path[2] || ''
      },
      tabType () {
        return this.path[3] || ''
      },
      callId () {
        return this.path[4] || ''
      },
      currentBusinessObj () {
        // 传递给客户模块的业务信息
        let dealSrc = ''
        if (this.tabType === 'webchat_todo') {
          dealSrc = 'popupWebchat'
        } else {
          dealSrc = 'relocationWebchat'
        }
        return {dealSrc: dealSrc, callId: this.callId, tabType: this.tabType, type: 'webchat'}
      },
      customer () {
        // todo webchat_todo列表里的定位客户的时候,这里没有执行,原因未知
        let currCustomer = {}
        if (this.$route.path.split('/')[2] === 'webchat') {
          if (this.tabType === 'webchat_todo' || this.tabType === 'webchat_all' || this.tabType === 'webchat_robot' || this.tabType === 'webchat_laterProcess' || this.tabType === 'webchat_queue') {
            currCustomer = this.$store.state.webchat.current[this.tabType].currentCustomer || {}
          }
        }
        this.customerId = currCustomer._id || ''
        let noCustomer = isEmpty(currCustomer)

        let phone = ''
        let name = ''
        let person = ''
        if (this.$store.state.webchat.autoCust[this.sessionId]) {
          phone = this.$store.state.webchat.autoCust[this.sessionId].autoCustPhone || ''
          name = this.$store.state.webchat.autoCust[this.sessionId].autoCustName || ''
          person = this.$store.state.webchat.autoCust[this.sessionId].autoContectPerson || ''
          let autoMatchContent = this.$store.state.webchat.autoCust[this.sessionId].autoMatchContent || ''
          let regPhone = /((\d{11,12})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/gm
          if (autoMatchContent) {
            if (regPhone.test(autoMatchContent)) {
              phone = autoMatchContent
            } else {
              name = autoMatchContent
            }
          }
        }
        var custByAuto = {name: name, phone: [{area: '', memo: person, tel: phone}]}

        return noCustomer ? {...custByAuto} : currCustomer
      }
      // ,
      // refreshWebchatRight () {
      //   return this.$store.state.webchat.current.refreshWebchatRight || 0
      // }
    },
    beforeMount () {
      this.$nextTick(() => {
        let arr = this.$route.path.split('/')
        if (arr[3] === 'webchat_todo') {
          if (arr.length > 4) {
            let list = this.$store.state.webchat.webchatList.webchat_todo.list
            if (list.length) {
              let flag = false
              for (let i = 0; i < list.length; i++) {
                if (list[i]._id === arr[4]) {
                  flag = true
                }
              }
              if (flag) {
                this.fetchData()
              } else {
                this.$store.commit('BLANK', 'webchat_todo')
                this.$router.push('/index/webchat/webchat_todo')
              }
            } else {
              this.$store.commit('BLANK', 'webchat_todo')
              this.$router.push('/index/webchat/webchat_todo')
            }
          } else {
            this.$store.commit('BLANK', 'webchat_todo')
            this.$router.push('/index/webchat/webchat_todo')
          }
        } else {
          this.fetchData()
        }
      })
    },
    mounted () {
      bus.$on('webchatShowBigImage', (data) => {
        this.webchatBigImage = true
      })
    },
    beforeDestroy () {
      bus.$off('webchatShowBigImage')
    },
    methods: {
      routerChange () {
        // this.playVideoReplay = false
        if ((this.tabType === 'webchat_all' || this.tabType === 'webchat_robot' || this.tabType === 'webchat_laterProcess' || this.tabType === 'webchat_queue') && this.cardLoading === false) {
          this.fetchData()
        }
      },
      showBigImage (data) {
        this.webchatBigImage = true
        this.bigImgUrl = data
      },
      videoReplay1 (data) {
        this.playVideoReplay = true
        this.videoReplayUrl = data.url
        this.videoReplatChatMsg = data.ChatMsg
      },
      closeVideoReplay () {
        this.playVideoReplay = false
        this.videoReplayUrl = ''
      },
      closeBigImage () {
        this.webchatBigImage = false
        this.bigImgUrl = ''
      },
      renderWebchatContainer () {
        bus.$emit('renderWebchatContainer', 'renderWebchatContainer is change')
        bus.$emit('changeCusComponents')  // 更新添加客户组件
        bus.$emit('changeCusSource')  // 更新客户的来源
        bus.$emit('changeCusStatus')  // 更新客户的状态
        bus.$emit('changeCusOwner')  // 更新客户的归属
        bus.$emit('changeCascader')  // 更新级联选项事件
      },
      fetchData () {
        console.log('Summary fetchData')
        this.loading = true
        this.cardLoading = true

        let type = this.type
        if (type !== 'webchat' || this.path.length <= 3) {
          this.cardLoading = false
          this.renderWebchatContainer()
          // this.$store.commit(types.RENDER_WEBCHAT_CONTAINER, Math.random()) // 去掉v-if后加载在线咨询右侧详情
          this.loading = false
          return
        }
        let webchatList = this.$store.state.webchat.webchatList[this.tabType].list
        let flag = true
        if (this.path.length > 4) {
          webchatList.forEach((item) => {
            if (item._id === this.callId) {
              flag = false
            }
          })
        }
        if (flag) {
          this.loading = false
          this.cardLoading = false
          this.renderWebchatContainer()
          return
        }
        let _id = this.callId
        this.sessionId = _id
        this.$emit('routeChange', this.tabType)
        let sid = ''
        let self = this
        // 翻页后该数据获取不到
        this.$store.state[type][type + 'List'][this.tabType].list.forEach(function (data) {
          if (data._id === _id) {
            sid = data.sid || ''
            self.sid = data.sid
            self.customerId = data.custId || ''
          }
        })
        let dealMsgFlag = false
        if (this.tabType === 'webchat_todo') {
          let currentSession = this.$store.state.webchat.current[this.tabType].currentSession[_id]
          let currentHistory = this.$store.state.webchat.current[this.tabType].messageList[_id]
          this.$store.state.webchat.webchatList.webchat_todo.list.forEach((item) => {
            if (item._id === this.sessionId && item.leakNum > 0) {
              dealMsgFlag = true
            }
          })
          if (currentSession && currentHistory) {
            // 切换后重新赋值webchat_todo下面的currentCustomer
            this.$store.commit(gtypes.SET_CURRENT_CUSTOMER, {data: this.$store.state.webchat.current[this.tabType].currentSession[_id].currentCustomer, type: 'webchat', tabType: 'webchat_todo', businessId: _id})
            this.cardLoading = false
            this.renderWebchatContainer()
            this.$store.commit(types.QUERY_WEBCHAT_CURRENT_SESSION, {_id: _id, tabType: this.tabType})
            this.sid = this.$store.state.webchat.current[this.tabType].currentSession[this.sessionId].sid || ''
            if (dealMsgFlag) {
              dealWebchatMsg(this.$store, {_id: _id, sid: sid, tabType: this.tabType}) // 会话未读数更新
            }
            this.loading = false
            return
          }
        }

        let importSid = ''
        if (this.$store.state.webchat.autoCust[_id]) {
          importSid = this.$store.state.webchat.autoCust[_id].importSid || ''
        }
        let info = {
          autoCustName: '',
          autoCustPhone: '',
          autoMatchContent: '',
          autoMatchType: '',
          autoCustLength: -1,
          autoCustObj: {},
          importSid: importSid
        }
        this.$store.commit('webchat/INIT_WEBCHAT_MESSAGELIST_SESSION', {sessionId: _id, tabType: this.tabType})
        this.$store.commit('webchat/AUTO_CUST_INFO', {sessionId: _id, data: info})
        const f1 = getWebchatDetail(this.$store, _id, sid, this.tabType)
        const f2 = getChatInfoById(this.$store, _id, sid, this.tabType)
        let that = this
        Promise.all([f1, f2]).then(function () {
          if (that.tabType === 'webchat_todo' && that.$store.state.webchat.current[that.tabType].chatInfoById[_id]) {
            let chatStatus = that.$store.state.webchat.current[that.tabType].chatInfoById[_id].status || ''
            if (chatStatus === 'changePeer') {
              // 加载会话的时候加载流转信息，但是流转消息的数据欠缺，暂时中止
              let platform = ''
              let sid = ''
              if (that.tabType === 'webchat_todo') {
                platform = that.$store.state.webchat.current[that.tabType].chatInfoById[_id].platform || ''
                sid = that.$store.state.webchat.current[that.tabType].chatInfoById[_id].sid || ''
              } else {
                platform = that.$store.state.webchat.current[that.tabType].chatInfoById.platform || ''
                sid = that.$store.state.webchat.current[that.tabType].chatInfoById.sid || ''
              }
              let data = {
                type: 'out',
                platform: platform,
                sid: sid,
                message: that.$t('webchat.changePeerOther'),
                _id: _id,
                contentType: 'text',
                content: that.$t('webchat.changePeerOther'),
                status: 'changePeer',
                uidDesc: that.$t('public.system')
              }
              that.$store.commit(types.UPDATE_WEBCHAT_MESSAGE_LIST, data)
            }
          }
          that.cardLoading = false
          that.renderWebchatContainer()
          that.loading = false
        }).then(() => {
          if (dealMsgFlag) {
            dealWebchatMsg(this.$store, {_id: _id, sid: sid, tabType: this.tabType}) // 更新会话未读数
          }
        })
      },
      unbundling () {
        this.$confirm(this.$t('public.unlinkCustomerPrompt'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.unbundlingFun()
        }).catch(() => {})
      },
      unbundlingFun () {
        let sName = ''
        let sessionId = this.$route.path.split('/')[4]
        if (this.tabType === 'webchat_todo') {
          sName = this.$store.state.webchat.current[this.tabType].chatInfoById[sessionId].sName
        } else if (this.tabType === 'webchat_all' || this.tabType === 'webchat_robot' || this.tabType === 'webchat_laterProcess' || this.tabType === 'webchat_queue') {
          sName = this.$store.state.webchat.current[this.tabType].chatInfoById.sName
        }
        this.$store.dispatch('deleteCustomerImRelation', {customerId: this.customer._id, sessionId: sessionId, sid: this.sid, sName: sName}).then((res) => {
          bus.$emit('changeCusComponents')  // 更新添加客户组件
          bus.$emit('changeCusSource')  // 更新客户的来源
          bus.$emit('changeCusStatus')  // 更新客户的状态
          bus.$emit('changeCusOwner')  // 更新客户的归属
          bus.$emit('changeCascader')  // 更新级联选项事件
        })
      }
    },
    components: {
      WebchatContainer,
      videoReplay,
      bigImage
    }
  }
  function updateCurrentWebchatList (store, sid, currentCustomer) {
    store.dispatch('updateCurrentWebchatListCustomer', {sid: sid, customer: currentCustomer})
  }
  function getWebchatDetail (store, _id, sid, submenu) {
    let data = {_id: _id, sid: sid, submenu: submenu}
    return store.dispatch('popupWebchat', data)
  }
  function getChatInfoById (store, _id, sid, submenu) {
    let data = {
      cust_id: '',
      queryHistory: true,
      submenu: submenu,
      _id: _id,
      sid: sid
    }
    return store.dispatch('queryChatInfoById', data)
  }
  function dealWebchatMsg (store, data) {
    return store.dispatch('dealMsg', data)
  }
</script>
<style lang="stylus" scoped>
</style>
